package com.dj.ms.support.sentinel;


import cn.hutool.core.util.StrUtil;
import com.dj.common.constants.ResponseStatus;
import com.dj.common.support.ResponseHandler;
import com.dj.common.support.ResponseListHandler;
import com.dj.common.support.ResponsePageHandler;
import feign.FeignException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Objects;

@Slf4j
@AllArgsConstructor
public class CustomFeignFallback<T> implements MethodInterceptor {

	private final Class<T> targetType;
	private final String targetName;
	private final Throwable cause;

	private static final String RESP = "CentralResponse";
	private static final String RESP_LIST = "CentralListResponse";
	private static final String RESP_PAGE = "CentralPageResponse";

	@Nullable
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		String errorMessage = cause.getMessage();
		log.error("FunFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(), targetName, errorMessage);
		// 非 FeignException，直接返回
		if (!(cause instanceof FeignException)) {
            //此处只是示例，具体可以返回带有业务错误数据的对象
			return genRst(method, ResponseStatus.HTTP_INTERNAL_ERROR, errorMessage);
		}
		FeignException exception = (FeignException) cause;
        //此处只是示例，具体可以返回带有业务错误数据的对象
		if (exception.responseBody().isPresent()) {
			errorMessage = String.valueOf(exception.responseBody().get());
		} else {
			errorMessage = "服务被熔断降级了";
		}
		return genRst(method, ResponseStatus.HTTP_LIMIT, errorMessage);
	}

	private Object genRst(Method method, int code, String msg) {
		Type t = method.getGenericReturnType();
		if (StrUtil.contains(t.getTypeName(), RESP)) {
			return ResponseHandler.fail(code, msg);
		}
		if (StrUtil.contains(t.getTypeName(), RESP_LIST)) {
			return ResponseListHandler.fail(code, msg);
		}
		if (StrUtil.contains(t.getTypeName(), RESP_PAGE)) {
			return ResponsePageHandler.fail(code, msg);
		}
		return ResponseHandler.fail(code, msg);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		CustomFeignFallback<?> that = (CustomFeignFallback<?>) o;
		return targetType.equals(that.targetType);
	}

	@Override
	public int hashCode() {
		return Objects.hash(targetType);
	}
}
